<!--
 * @Descripttion: 
 * @Author: voanit
 * @Date: 2022-04-07 15:17:06
 * @LastEditors: voanit
 * @LastEditTime: 2022-04-07 17:53:02
-->
<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :http-request="handleClick"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload
    >=={{ imageUrl }}
  </div>
</template>

<script>
export default {
  name: "uploadImg",
  data() {
    return {
      imageUrl: "",
    };
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    handleClick({ file }) {
      console.log(file, "handleClick");
      /*
      http-request 添加这个属性，就会覆盖默认的 action行为，做了一个自定义操作
      :on-success  就不会再触发==删除这个配置
      */
      /* 1-导入sdk包文件  使用第三方sdk来实现图片上传 */
      var COS = require("cos-js-sdk-v5");
      /* 2-填写秘钥 */
      var cos = new COS({
        SecretId: "AKID2tTmoZ3IGwLUMxHJ5ZmiOmtjIaaJlwrV",
        SecretKey: "OWNxFH1UgbFchVGkxtZx4tRiiQs51f28",
      });
      /* 3-填写存储桶配置项 */
      cos.putObject(
        {
          Bucket: "supercxy-1310935156" /* 必须 */,
          Region: "ap-nanjing" /* 存储桶所在地域，必须字段 */,
          Key: file.name /* 必须 /* 文件名  */,
          StorageClass: "STANDARD", // 上传模式, 标准模式
          Body: file, // 上传文件对象
          onProgress: function (progressData) {
            console.log(JSON.stringify(progressData));
          },
        },
        (err, data) => {
          // console.log(err || data);
          // console.log(this, 9);
          this.imageUrl = "https://" + data.Location;
        }
      );
    },
  },
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
